<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Http\Requests;
use App\Http\Controllers\Controller;
use Illuminate\Queue\Capsule\Manager;
use Session;
use DB;
use Illuminate\Support\Facades\Input;
use Illuminate\Support\Facades\Redirect;
use Illuminate\Support\Facades\Log;
use App\Http\Requests\CreateBankShopRequest;
use App\Http\Requests\UpdateBankShopRequest;
use App\BankShop;
use App\User;
use App\UserRole;
use Illuminate\Support\Facades\Auth;

class BankShopController extends Controller
{
    public function __construct()
    {
        $this->middleware('auth');
    }

	public function index(Request $request) {
		// 查看当前菜单可使用的功能按钮
		$uri = $request->path();
		$data['optionArr'] =  $this->checkMenuOption($uri);

		$bankShop = BankShop::where('state','!=',-1)->get();
//		dd($bankShop);

		$data['bankShop'] = $bankShop;

		return view('bankShop.list')->with($data);
	}

    public function create(Request $request)
    {
        return view('bankShop.create');
    }


    public function store(CreateBankShopRequest $request){
//        Log::info(__FILE__.__LINE__."新增数据保持");
        DB::beginTransaction();
        $bankShop = new BankShop();
        $bankShop->code =$request->code;
        $bankShop->address =$request->address;
        $bankShop->longitude =$request->longitude;
        $bankShop->latitude =$request->latitude;
        $bankShop->shopName =$request->shopName;
        $bankShop->contact =$request->contact;
        $bankShop->phone =$request->phone;
        $bankShop->contact_email =$request->contact_email;
        $bankShop->busStartTime =$request->busStartTime;
        $bankShop->BusEndTime =$request->BusEndTime;
        $bankShop->state =1; // 默认启用状态
	    if(!$bankShop->save()){
		    DB::rollback();
		    return redirect()->back()->withInput();
	    }

	    // 网点新增成功，创建后台系统登录账号
	    $users = new User();
	    $users->name =$request->phone;  // 账号
	    $users->email =$request->contact_email; // 邮箱
	    $users->password = bcrypt(111111); // 默认密码
	    $users->username =$request->shopName;  // 网点名称
	    if(!$users->save()){
		    DB::rollback();
		    return redirect()->back()->withInput();
	    }
		// 保存用户角色信息
	    $userRole = new UserRole();
	    $userRole->user_id = $users->id;
	    $userRole->role_id =3;
	    if(!$userRole->save()){
		    DB::rollback();
		    return redirect()->back()->withInput();
	    }
	    DB::commit();

	    $adminUser = Auth::user();
	    if($adminUser){
		    $userId = $adminUser->id;
		    $logs = $adminUser->name.'在'.date('Y-m-d H:i:s').' 新增了【  '.$request->shopName.' 】网点';
		    adminOperationLog($request,$userId,$logs);
	    }
	    return redirect('bankShop/list')->with('success','新增成功');
    }


	public function showEp($id)
	{
		// 获取网点下绑定的设备
		$shopEquipment = BankShop::getShopEquipment($id);
//		dd($shopEquipment);

		$data['shopEquipmentInfo'] = $shopEquipment;

		return view('bankShop.showEp')->with($data);

	}

	public function showOrder($id)
	{
		// 获取网点下的订单
		$shopOrderObj = BankShop::getShopOrderS($id);
//		dd($shopOrderObj);

		$data['shopOrderInfo'] = $shopOrderObj;

		return view('bankShop.showOrder')->with($data);

	}


    public function edit($id)
    {
        $bankShop = BankShop::find($id);
        $data['bankShopInfo'] = $bankShop;

        return view('bankShop.edit')->with($data);

    }


    public function update(UpdateBankShopRequest $request, $id){

        DB::beginTransaction();
        $bankShop = BankShop::find($id);
        $oldPhone = $bankShop->phone;
	    //如果新的账号与原来不一样，修改过，如果修改了，则删除原来的管理员账号，重新创建
        if(trim($oldPhone) != trim($request->phone)){
			// 删除原来的账号、删除角色
	        $userId = User::where('name',$oldPhone)->pluck('id')->toArray()[0];
	        $affectId = User::where('name',$oldPhone)->delete();
	        if($userId){
		        $affectId = UserRole::where('user_id',$userId)->delete();
	        }
        }

        $bankShop->code =$request->code;
        $bankShop->address =$request->address;
        $bankShop->longitude =$request->longitude;
        $bankShop->latitude =$request->latitude;
        $bankShop->shopName =$request->shopName;
	    $bankShop->contact =$request->contact;
        $bankShop->phone =$request->phone;
	    $bankShop->contact_email =$request->contact_email;
	    $bankShop->busStartTime =$request->busStartTime;
	    $bankShop->BusEndTime =$request->BusEndTime;

        if(!$bankShop->save()){
            DB::rollback();
            return Redirect::back()->withInput()->withErrors(['fail' => trans('message.updateFail')]);
        }

	    // 成功，创建后台系统登录账号
	    $users = new User();
	    $users->name =$request->phone;  // 账号
	    $users->email =$request->contact_email; // 邮箱
	    $users->password = bcrypt(111111); // 默认密码
	    $users->username =$request->shopName;  // 网点名称
	    if(!$users->save()){
		    DB::rollback();
		    return redirect()->back()->withInput();
	    }
	    // 保存用户角色信息
	    $userRole = new UserRole();
	    $userRole->user_id = $users->id;
	    $userRole->role_id =3;
	    if(!$userRole->save()){
		    DB::rollback();
		    return redirect()->back()->withInput();
	    }


        DB::commit();

	    $adminUser = Auth::user();
	    if($adminUser){
		    $userId = $adminUser->id;
		    $logs = $adminUser->name.'在'.date('Y-m-d H:i:s').'编辑了【 '.$request->shopName.' 】网点';
		    adminOperationLog($request,$userId,$logs);
	    }

        return Redirect::to(url('bankShop/list'))->with('success', trans('message.updateSuccess'));

    }

    // 修改门店状态
    public function changShopState(Request $request){
		$id = $request->id;

		$state = $request->state;

	    if(!$id || !$state){
		    return -1;
	    }

	    $bankShop = BankShop::find($id);
	    if($bankShop){
		    $bankShop->state = $state;
		    $bankShop->save();

		    $name = BankShop::getNameById($id);
		    $adminUser = Auth::user();
		    if($adminUser){
			    $userId = $adminUser->id;
			    $logs = $adminUser->name.'在'.date('Y-m-d H:i:s').'修改了【 '.$name.' 】网点状态';
			    adminOperationLog($request,$userId,$logs);
		    }

		    return 1;
	    };
	    return -1;
    }

    public function delete(Request $request){

    	$bid = $request->id;
        if(!$bid){
            return '-1';
        }
	    $name = BankShop::getNameById($bid);

        DB::beginTransaction();
        //  del   删除网点
//	    $affectId= BankShop::where('id',$bid)->update([
//		    'state'=>-1
//	    ]);
//	    var_dump($affectId);

        $affectId = BankShop::where('id',$bid)->delete();
        if(!$affectId){
            DB::rollback();
            return -1;
        }
		$phone = BankShop::getPhoneById($bid);
        $userId = User::getIdByName($phone);
        // 删除网点后，删除账号表、账号和角色关系表
	    $aid = User::where('name',trim($phone))->delete();
	    if(!$aid){
		    DB::rollback();
		    return -1;
	    }
	    $aid = UserRole::where('user_id',$userId)->delete();
	    if(!$aid){
		    DB::rollback();
		    return -1;
	    }
        DB::commit();

	    $adminUser = Auth::user();
	    if($adminUser){
		    $userId = $adminUser->id;
		    $logs = $adminUser->name.'在'.date('Y-m-d H:i:s').'删除了网点：【 '.$name.' 】';
		    adminOperationLog($request,$userId,$logs);
	    }

        return 1;

    }





}





